package security;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.UserManager;

import entities.User;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	UserManager userManager;
	
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get");
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("post");
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(user);
		if(user == null){
			String username = (String) request.getParameter("username");
			String password = (String) request.getParameter("password");
			
			user = userManager.getLoggedInUser(username);
			
			if(user.getPassword().equals(Encryption.digest(password))){
				request.getSession().setAttribute("user", user);
				request.getRequestDispatcher("WEB-INF/Overview.jsp").forward(request, response);
			}else{
				response.sendRedirect("index.jsp");
			}
		}else{
//			request.getSession().setAttribute("user", user);
			request.getRequestDispatcher("WEB-INF/Overview.jsp").forward(request, response);
		}		
	}

}
